package com.sun.controller;

import com.alibaba.fastjson.JSONObject;
import com.sun.model.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class DeptConsumerController {

    //那么此时该怎么调用service的功能呢？不在一起，服务部署在服务器上
    // (url,实体：map,ReturnClass<T>)

    //private static final String REQUEST_BASE_URL = "http://localhost:8001";

    //ribbon实现负载均衡应该指定服务的名称
    private static final String REQUEST_BASE_URL = "http://SPRINGCLOUD-PROVIDER-DEPT";

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/consumer/{id}")
    public Dept getDeptById(@PathVariable("id") Integer id) {
        //带有参数的get请求
        Map paramMap = new HashMap();
        paramMap.put("id",2);
        paramMap.put("userName","zhangsan");
       // Dept dept = restTemplate.getForObject(REQUEST_BASE_URL + "/dept/get/" + id, Dept.class,paramMap);
        Dept dept = restTemplate.getForObject(REQUEST_BASE_URL + "/dept/get/" + id, Dept.class);
        return dept;
    }

    @RequestMapping("/consumer/add")
    public boolean getDeptById(Dept dept) {
        //post带有参数的请求，参数不用使用Map(有点坑) 使用Spring提供的MultiValueMap
        MultiValueMap multiValueMap = new LinkedMultiValueMap();
        multiValueMap.put("id",23);
        multiValueMap.put("userName","zhangsan");
        //restTemplate.postForObject(REQUEST_BASE_URL + "/dept/add",dept, boolean.class,multiValueMap)

        //或者通过如下方式
        JSONObject msg = new JSONObject();
        msg.put("id",23);
        msg.put("userName", "lisi");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity request = new HttpEntity(msg.toJSONString(), headers);
        //restTemplate.postForObject(REQUEST_BASE_URL + "/dept/add",dept, boolean.class,request);
        return restTemplate.postForObject(REQUEST_BASE_URL + "/dept/add",dept, boolean.class);
    }

    @RequestMapping("/consumer/list")
    public List<Dept> getDeptList() {
        return restTemplate.getForObject(REQUEST_BASE_URL + "/dept/getAll", List.class);
    }


}
